{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# On-Site Question 3 - SOLUTION\n",
    "\n",
    "## Problem\n",
    "\n",
    "** Create a function that takes in a list of unsorted prices (integers) and a maximum possible price value, and return a sorted list of prices**\n",
    "\n",
    "## Requirements\n",
    "\n",
    "** Your function should be able to perform this in less than O(nlogn) time. **"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Solution\n",
    "\n",
    "We can actually solve this problem by using a [*counting sort*](https://en.wikipedia.org/wiki/Counting_sort). Basically a counting sort works well when you know the range of integer values you will have ahead of time.\n",
    "\n",
    "Read the wikipedia article linked above for a full break down, and an implementation is here below (using the prices situation described in the problem above)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def solution(unsorted_prices,max_price):\n",
    "    \n",
    "    # list of 0s at indices 0 to max_price\n",
    "    prices_to_counts = [0]* (max_price+1)\n",
    "    \n",
    "    # populate prices\n",
    "    for price in unsorted_prices:\n",
    "        prices_to_counts[price] +=1\n",
    "        \n",
    "    # populate final sorted prices\n",
    "    sorted_prices = []\n",
    "    \n",
    "    # For each price in prices_to_counts\n",
    "    for price,count in enumerate(prices_to_counts):\n",
    "        \n",
    "        # for the number of times the element occurs\n",
    "        for time in range(count):\n",
    "            \n",
    "            # add it to the sorted price list\n",
    "            sorted_prices.append(price)\n",
    "            \n",
    "    return sorted_prices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 4, 6, 7, 8, 9]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "solution([4,6,2,7,3,8,9],9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This was a great exercise in learning about a new sorting algorithm, make sure to read up on it and practice this problem again!\n",
    "\n",
    "# Good Job!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
